<script setup>
import {getOrderDetails} from '@/api/order'
import {productComment} from '@/api/product'
import { formatDateTime, formatPrice } from "@/utils/index.js"
import { showToast } from 'vant'
import useUserStore from '@/store/modules/user'
import {t} from '@/locales'

const useUser = useUserStore()
const {proxy} = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const orderDetail = ref({details: []})
// 上传图片列表
const requestHeaders = {
  Authorization: 'Bearer ' + useUser.token
}
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址

const commentNum = computed(() => {
  return orderDetail.value.details.filter(it => it.score>0)?.length || 0
})

// 上传图片
const fileList = ref([])
const imgUrlList = ref([])
const afterRead = (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  fetch(uploadImgUrl.value, {
    method: 'POST',
    body: formData,
    headers: requestHeaders,
  }).then(response => response.json()).then(data => {
    imgUrlList.value.push({...data.data, fileName: file.file.name})
  }).catch(error => {
    console.error('error:', error);
  });
};
function delImg(file) {
  const i = imgUrlList.value.findIndex(it => it.fileName===file.file.name)
  imgUrlList.value.splice(i, 1)
}
function goBack() {
  const { id } = orderDetail.value
  const path = route.query.form==='center'?'':`-detail?id=${id}`
  router.push(`/order${path}`)
}
// 提交评论
function submitComment() {
  const { id, details } = orderDetail.value
  const commentSet = details.map(it => {
    return {
      skuId: it.skuId,
      productId: it.productId,
      comment: it.comment,
      score: it.score,
      imageUrls: imgUrlList.value.map(it => it.url)
    }
  })
  productComment({orderId: id, commentSet}).then(r => {
    showToast(t('order.commentSuc'))
    goBack()
  })
}
function init() {
  getOrderDetails(route.query.id).then(r => {
    const rData = r.data
    rData.details.forEach(it => {it.fileList = []})
    orderDetail.value = rData
  })
}

init()
</script>

<template>
  <div class="p-comment">
    <div class="comment-num">
      {{$t('order.writeComment')}}<span>{{commentNum}}/{{ orderDetail.details.length }}</span>
    </div>
    <div class="comment-list">
      <div
        class="comment-item"
        v-for="item in orderDetail.details"
      >
        <div class="pro-cell">
            <img :src="item.image">
            <div class="r-p">
              <div class="name-cell">
                <p>{{item.productName}}</p>
                <p>
                  <span class="sku-tit">{{t('order.sku')}}：</span>
                  <span class="sku-value">{{item.sku}}</span>
                </p>
              </div>
              <div class="price-num">
                <p>{{formatPrice(item.originalPrice)}}</p>
                <p>{{item.num}}</p>
              </div>
            </div>
        </div>
        <div class="comment">
          <div class="score">
            <span class="label">{{ $t('order.comment') }}</span>
            <van-rate v-model="item.score" :allow-half="true"/>
          </div>
          <van-field
            v-model="item.comment"
            :placeholder="$t('order.commentTip')"
            :maxlength="500"
            type="textarea"
          />
          <div class="upload-img">
            <p class="label">{{ $t('order.uploadImg') }}</p>
            <van-uploader
                v-model="fileList"
                multiple
                :after-read="afterRead"
                @delete="delImg"
                :max-count="9"
            />
            <div class="number-uploads">{{t('afterSale.inAll')}}<b>{{fileList.length}}</b>{{t('afterSale.severalPiecesOf')}}<b>{{9 - fileList.length}}</b>{{t('afterSale.piece')}}</div>
          </div>
        </div>
      </div>
    </div>
    <van-sticky position="bottom">
      <div class="btn-list">
        <van-button class="s-btn line-btn w-auto" @click="goBack">{{$t('common.cancel')}}</van-button>
        <van-button class="s-btn w-auto" @click="submitComment" :disabled="commentNum!==orderDetail.details.length">{{$t('common.confirm')}}</van-button>
      </div>
    </van-sticky>
  </div>
</template>

<style scoped lang="scss">
.p-comment {
  .comment-num {
    font-size: 18px;
    padding: 16px 16px 0;
    span {
      font-size: 14px;
      color: #8C8C8C;
      margin-left: 8px;
    }
  }
  .comment-list {
    .comment-item {
      padding: 24px 0;
      &:nth-child(n + 2) {
        border-top: 8px #F8F8F8 solid;
      }
      .pro-cell {
        padding: 0 16px;
        display: flex;
        height: 110px;
        margin-bottom: 24px;
        img {
          width: 98px;
          height: 100%;
        }
        .r-p {
          flex: 1;
          display: flex;
          padding-left: 12px;
          flex-direction: column;
          justify-content: space-between;
          .name-cell {
            p {
              &:first-child {
                font-weight: 600;
                font-size: 14px;
              }
              &:last-child {
                font-size: 12px;
                .sku-tit {
                  color: #666666;
                }
              }
            }
          }
          .price-num {
            display: flex;
            justify-content: space-between;
            p {
              &:first-child {
                font-weight: 600;
                font-size: 14px;
              }
              &:last-child {
                font-size: 12px;
                color: #8C8C8C;
              }
            }
          }
        }
      }
      .comment {
        padding: 0 16px;
        font-size: 14px;
        .score {
          margin-bottom: 18px;
          .label {
            margin-right: 40px;
            vertical-align: bottom;
          }
          :deep(.van-rate__icon--full) {
            color: #262626;
          }
        }
        .van-field {
          border-radius: 2px 2px 2px 2px;
          border: 1px solid #E5E5E5;
          height: 150px;
          margin-bottom: 16px;
        }
        .upload-img {
          .label {
            font-size: 14px;
            color: #8C8C8C;
            margin-bottom: 8px;
          }
          .number-uploads {
            font-size: 12px;
            color: #8C8C8C;
          }
        }
      }
    }
  }
  :deep(.van-sticky) {
    border-top: 1px #ECEBF0 solid;
    background: #FFFFFF;
  }
  .btn-list {
    display: flex;
    padding: 8px 16px;
    column-gap: 12px;
    .s-btn {
      flex: 1;
    }
  }
}
</style>